package com.sophie.chapter7;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

/**
 * 获取监控指标
 */
public class JmxConnection {

    private String ipAndPort;

    private String jmxURL;

    private MBeanServerConnection conn;

    public JmxConnection(String ipPort) {
        this.ipAndPort = ipPort;
    }

    public boolean init() {
        jmxURL = "service:jmx:rmi:///jndi/rmi://" + ipAndPort + "/jmxrmi";
        try {
            JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
            JMXConnector connector = JMXConnectorFactory.connect(serviceURL, null);
            conn = connector.getMBeanServerConnection();
            if (conn == null) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public double getMsgInPerSec() {
        String objName = "kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec";
        try {
            ObjectName objectName = new ObjectName(objName);
            Object object = conn.getAttribute(objectName, "OneMinuteRate");
            if (object != null) {
                return (double) (Double) object;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0.0;
    }

    public static void main(String[] args) {
        JmxConnection jmxConnection = new JmxConnection("localhost:9999");
        jmxConnection.init();
        System.out.println(jmxConnection.getMsgInPerSec());
    }
}